<template>
    <massif-layout leftWidth="300px" :showBack="true" @back="goBack">
        <template v-slot:left>
            <div class="receive-land-left-view">
                <div class="mass-view">
                    <div class="name">已选地块 <span style="color: #00b070;font-size:15px;">({{selectLandList.length}})</span></div>
                    <div style="color: #00b070;font-size:14px;">{{getMapSize}}(亩)</div>
                </div>
                <div>
                    <div> 
                        <el-input placeholder="搜索地块名称" clearable v-model="sreachText" >
                            <template #append>
                                <vxe-icon name="search" size="mini"></vxe-icon>
                            </template> 
                        </el-input>
                    </div>
                    <div class="filter-view">
                        <el-select v-model="selectText"  style="width:120px;" clearable placeholder="全部">
                            <el-option v-for="item in groupList" :label="item.groupName" :value="item.landGroupId"></el-option>
                        </el-select>
                         <vxe-button mode="text" v-if="showFooter" @click="btnAllDel"  icon="vxe-icon-delete" size="small" status="danger" content="清空"></vxe-button>
                    </div>
                    <landList :tableData="getLandDataList" :showDel="showFooter" @onClick="setMapData" @onDelete="delCell" />
                </div>
            </div>
        </template>
        <div class="right-view-map">
            <vxe-button mode="text" size="small" @click="btnBack" style="position: absolute;top:10px;right:10px;z-index:999;" icon="vxe-icon-arrow-left">返回</vxe-button>

          <mapContainer @init="initMap" @zoom="zoomMap" :searchPanel="false" @click="clickMap"  @pointerMove="pointerMove" />
          <div class="groug-change-view">
            <div class="groug-list">
                <div class="item on">已选地块</div>
                <div class="item">未选地块</div>
            </div>
          </div>
          <div class="groug-view">
            <div class="groug-list">
                <div class="item"
              @click="btnChooseGroug('')"
              :class="landGroupId==''?'on':''">全部地块</div>
              <div class="item"
              v-for="item in groupList"
              @click="btnChooseGroug(item)"
              :class="item.landGroupId==landGroupId?'on':''">{{item.groupName }}</div>
            </div>
          </div>
          <div class="groug-right-view" v-if="showFooter">
            <div>提示：点击选择或切换分组来选择地块</div>
            <div class="choose-land">
                <el-checkbox v-model="checkedLand" @change="changeCheckBox"></el-checkbox> 全选地块
            </div>
            <vxe-button mode="text" 
            status="primary" 
            size="small" 
            @click="saveLand"
            :content="`确定 (${selectLandList.length})`" icon="vxe-icon-check"></vxe-button>
          </div>
        </div>
        <PoiPopup v-if="showPop &&currentZoom>12" :popOption="popObjct"   @onClose="(type)=>{showPop=type}" />
    </massif-layout>
</template>
  
  <script setup>  
  import { nextTick, ref, watch, onActivated,reactive,onMounted,computed} from 'vue'
  import{useRouter,useRoute} from "vue-router"
  import {getLandList,getLandGroupList} from '@/api/plant'
  import {message} from '@/utils/element'
  import massifLayout from '../components/layout.vue'
  import groupSelect from '@/components/custom/groupSelect.vue'
  import landSelect from '@/components/custom/landSelect.vue'
  import cDialog from '@/components/custom/cDialog.vue'
  import { useUserStore } from '@/pinia/modules/user'
  import cropSelect from '@/components/custom/cropSelect.vue'
  import Image from '@/components/custom/image.vue'
  import CountUp from 'vue-countup-v3'
  import landList from './components/landList.vue'
  import  mapContainer from '@/components/Map/index.vue'
  import {WktToPolygon } from '@/components/Map/utils/geoToWkt';
  import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"
  import Graphic from "@arcgis/core/Graphic"
  import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
  import PoiPopup from '@/components/Map/components/PoiPopup.vue';
  import Point from '@arcgis/core/geometry/Point.js';
  import {VXETable} from 'vxe-table'
  const emit = defineEmits(['close','change'])
  const router = useRouter()
  const userStore = useUserStore()
  const dropFarmLandId = ref('')
  const dropFarmLandNo = ref('') 
  const dropFarmLandPic = ref('') 
  const tableData = ref([])
  const selectLandList = ref([])
  const currentZoom= ref(5)
 const clickRow = ref(null)
 const showPop = ref(false)
 const checkedLand = ref(false)
 const sreachText = ref('')
 const selectText = ref('')
 const groupList = ref('')
 const landGroupId = ref('')
 const popObjct = ref({})
 let mapView =null
 let graphicsLayer = null
 const props = defineProps({
    dataList: {
    type: Array,
    default: []
  },
  selectList: {
    type: Array,
    default: []
  },
  openCount:{
    type: Number,
    default: 1
  },
  showFooter:{
    type: Boolean,
    default: true
  }
})


watch(()=>props.dataList,(n,o)=>{
  if(props.dataList.length>0){
    drawLandList(props.dataList)
    tableData.value =props.dataList
    checkedLand.value =tableData.value.length ==selectLandList.value.length
  }
})
watch(()=>props.selectList,(n,o)=>{
  if(props.selectList.length>0){
      selectLandList.value =props.selectList
      checkedLand.value =tableData.value.length ==selectLandList.value.length
      changeLandColor()
  }else{
    selectLandList.value =[]
    checkedLand.value=false
    changeLandColor()
  }
})

onMounted(()=>{})
  const initMap = (map)=>{
    mapView = map
    tableData.value =props.dataList
    selectLandList.value =props.selectList
    checkedLand.value =tableData.value.length ==selectLandList.value.length
    if(props.dataList.length>0){
      drawLandList(props.dataList)
    }
    getLandGroupList({farmId:userStore.userInfo.farmId}).then((res)=>{
        if(res.success){
            groupList.value = res.data ||[]
        }
       })
  }

  const btnChooseGroug =(row)=>{
    landGroupId.value =row?.landGroupId||''
    if(landGroupId.value){
      let list1=  tableData.value.filter((item)=>{return item.landGroupId == landGroupId.value})
      let list2= selectLandList.value.filter((item)=>{return item.landGroupId == landGroupId.value})
      checkedLand.value =list1.length ==list2.length
      
    }else{
        checkedLand.value =tableData.value.length ==selectLandList.value.length
    }

     if(graphicsLayer){
        let graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type != 'text')
        graphics.forEach(item => {
                if(item.attributes.landGroupId == landGroupId.value || landGroupId.value==''){
                    item.visible =true
                }else{
                    item.visible =false
                }
        })
        mapView.goTo(graphics.filter((item)=>{return item.attributes.landGroupId==landGroupId.value|| landGroupId.value==''}));
   }
  }

  const changeCheckBox =(val)=>{
      if(landGroupId.value==''){
        selectLandList.value = val?tableData.value:[]
      }else{
        let landObj = tableData.value.filter((item)=> {return item.landGroupId == landGroupId.value})
        selectLandList.value = val? selectLandList.value.concat(landObj):selectLandList.value.filter((item)=>{
            return item.landGroupId != landGroupId.value
        })
      }
      changeLandColor()
  }

  const saveLand =()=>{
    emit('change',selectLandList.value)
    btnBack()
  }

  const getMapSize = computed(()=>{
    let totalSize=0
    selectLandList.value.forEach((item)=>{
        totalSize+=item?.mapAreaSize||0
    })
    return totalSize.toFixed(1)
  })

  const getLandDataList = computed(()=>{
    if(sreachText.value!='' && selectText.value!=''){
        return selectLandList.value.filter((item)=>{return item.farmLandName.indexOf(sreachText.value)>=0 && item.landGroupId==selectText.value})
    }
    if(sreachText.value!=''){
        return selectLandList.value.filter((item)=>{return item.farmLandName.indexOf(sreachText.value)>=0})
    }
    if(selectText.value!=''){
        return selectLandList.value.filter((item)=>{return item.landGroupId==selectText.value})
    }
    return selectLandList.value
  })

const zoomMap=(val)=>{
  currentZoom.value = val
  if(graphicsLayer){
        const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type == 'text')
        graphics.forEach(item => {item.visible = val > 17 ? true : false})
   }
   getClickData()
}

const pointerMove=(val)=>{
   getClickData()
}


//选中-地块改变颜色
const changeLandColor =()=>{
        if (graphicsLayer) {
            graphicsLayer.graphics.items.forEach(item => {
                item.symbol = {
                        type: 'simple-fill',
                        color:'#25c28900',
                        outline: {
                            color: '#25c289',
                            width: 1
                        }
                }
            })
            selectLandList.value.forEach((attrs)=>{
             const target = graphicsLayer.graphics.items.find((item) => item.attributes.farmLandId == attrs.farmLandId);
             if (target) {
                    target.symbol = {
                        type: 'simple-fill',
                        color:'#25c289',
                        outline: {
                            color: '#25c289',
                            width: 1
                        }
                }
            }
            
        })
     }
}

const delCell=(index)=>{
    selectLandList.value.splice(index,1)
    changeLandColor()
}

const btnAllDel =()=>{
    selectLandList.value=[]
    changeLandColor()
    btnChooseGroug({landGroupId:landGroupId.value})
}

const clickMap =(e,e2)=>{
     if(e2.results.length>0){
          e2.results.forEach(e3 => {
          let attrs = e3.graphic.attributes
         if(attrs?.class == "click-landMark") { 
           let data = selectLandList.value.find((item)=>item.farmLandId == attrs.farmLandId)
           if(data?.farmLandId){
            selectLandList.value= selectLandList.value.filter((item)=>{return item.farmLandId != attrs.farmLandId})
           }else{
            selectLandList.value.push(attrs)
           }
           changeLandColor()
          }
        })
      }
 }

//地块绘制到地图
const drawLandList = (dataList,center,onType)=>{
  if(!graphicsLayer){
    graphicsLayer = new GraphicsLayer({ id:'select-land-plot'});
  }else{
    //graphicsLayer.removeAll()
  }
  dataList.forEach((item,index)=>{
    const graphics = graphicsLayer.graphics.items.find((m) => m.attributes.farmLandId == item.farmLandId)

    if(item?.geom && !graphics){
        const geo = WktToPolygon(item.geom, { wkid: 4326 });
        const newGeo = webMercatorUtils.geographicToWebMercator(geo)
        const polygon = new Graphic({
          geometry: newGeo,
          symbol: {
            type: 'simple-fill',
            color:'#25c28900',
            outline: {
                color: '#25c289',
                width: 1
            }
          },
          attributes: {
            class: 'click-landMark',
            farmLandId:item.farmLandId,
            ...item
          }
          })
          const textAreaStyle = {
              type: "text", 
              color: [255, 255, 255],
              haloColor: [0, 0, 0],
              haloSize: "1px",
              text: "",
              xoffset: 0,
              yoffset: 0,
              cursor: 'pointer',
              font: {
                size: 10,
                family: "PingFangSC",
                weight: "bold"
              }
          }
          const AreaGeometry = polygon.geometry.extent.center
          const areaValue = Number(item.mapAreaSize.toFixed(1))
          let result = "";
          for (let i = 0, len = item.farmLandName.length; i < len; i++) {
            if (i % 8 === 0 && i != 0) result += '\n';
            result += item.farmLandName[i];
            }
          textAreaStyle.text = `${result}\n${areaValue}亩`
          const textAttr = { ...item, type: 'text' }
          const textAreaGraphic = new Graphic({
              geometry: AreaGeometry,
              symbol: textAreaStyle,
              attributes: textAttr,
              visible: currentZoom.value>14?true:false
            })
            const graphics = graphicsLayer.graphics.items.filter((m) => m.attributes.farmLandId == item.farmLandId)
            if(!graphics.length){
                graphicsLayer.add(polygon);
                graphicsLayer.add(textAreaGraphic)
            }
     }
  })
    //画边形
    mapView.map.add(graphicsLayer)
    mapView.whenLayerView(graphicsLayer).then((event) => {
      setTimeout(() => {
        if(event?.lastUpdateId>0 && props.openCount==1){
        VXETable.modal.close('loading-land')
        }
        if(event?.lastUpdateId<0 && props.openCount==2){
          VXETable.modal.close('loading-land')
        } 
      }, 1500);
    })
    //定位
    setTimeout(() => {
        mapView.goTo(graphicsLayer.graphics.items);
        changeLandColor()
    }, 500);
}

  // 设置选中高亮
const setSelectLine = ({ row, rowIndex }) =>{
    if(row.farmLandId == dropFarmLandId.value){
        return "selectedStyle"
    }else{
        return ''
    }
  }

  
//点击坐标点的弹出框数据
const getClickData = ()=>{
  if(!clickRow.value){return}
  let item = clickRow.value
  const mapPoint = new Point({longitude: item.locationLongitude,latitude: item.locationLatitude, spatialReference: {wkid: 4326}});
   const { x, y } = mapView.toScreen(mapPoint)
   item.x = x
   item.y = y
  const popOption = {
            title:item.farmName||item.farmLandNo,
            farmId:item.farmId,
            companyId:item.companyId,
            farmLandId:item.farmLandId,
            pic:item.pic,
            screenX: item.x+10,
            screenY: item.y+10,
            visible:true,
            mapX: item.longitude,
            mapY: item.latitude,
            btnText:'地块详情',
            values: [
                // {
                //     label: '所属农场',
                //     value: item.farmName
                // },
                {
                    label: '地块编号',
                    value: item.farmLandNo
                },
                {
                    label: '地块名称',
                    value: item.farmLandName
                },
                {
                    label: '地块面积',
                    value:  Number(item.mapAreaSize.toFixed(1))+'亩'
                },
                {
                    label: '位置',
                    value: item.locationAddress
                }
            ],
            ...item
  }
  popObjct.value = popOption
}
  // 表格行单击处理事件
  const setMapData = (row)=>{
    dropFarmLandId.value = row.farmLandId
    dropFarmLandPic.value = row.pic
    dropFarmLandNo.value = row.farmLandNo
    setSelectLine({row})
    const graphics = graphicsLayer.graphics.items.filter((m) => m.attributes.farmLandId == row.farmLandId)
    mapView.goTo(graphics);
        // mapView.set({
        // zoom:18,
        // center: [Number(row.locationLongitude), Number(row.locationLatitude)]
        // })
    clickRow.value = row
    showPop.value = true
    getClickData()
  }

  const btnBack = ()=>{
    emit('close')
  }

  </script>
<style>
.filter-view .el-select .el-input__inner{
    background-color: #f5f7fa;
}
</style>
<style lang="scss" scoped>
.receive-land-left-view{
        box-sizing: border-box;
        display: flex;
        flex-flow: column;
        height: 100%;
        padding: 0;
        //overflow: hidden;
        .mass-view{
            display: flex;
            justify-content: space-between;
            padding: 6px 10px;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
            .name{
                font-size:15px;
                font-weight: bold;
                color: #333;
                position: relative;
                &::after{
                    position: absolute;
                    contain: '';
                    content:'';
                    height:16px;
                    width:2px;
                    background-color: #04AE70;
                    left: -5px;
                }
            }
        }
      .filter-view{
          display: flex;
          justify-content: space-between;
          align-items: center;
          background-color: #f5f7fa;
          padding:6px 0;
          .el-input__inner{
            background-color: #f5f7fa;
          }
      }
}


.right-view-map{
    height: calc(100vh - 115px);
    position: relative;
    width:100%;
    .groug-change-view{
        position: absolute;
        bottom:60px;
        left:10px;
        z-index:99; 
        border:1px solid #a9a8a8;
        .groug-list{
            background-color: #00000080;
            .item{
                height:36px;
                line-height:36px;
                padding:0 10px;
                font-size:13px;
                color: #fff;
                position: relative;
                text-indent: 25px;
            }::after{
               position: absolute;
               height:10px;
               width:20px;
               border:1px solid #04AE70;
               content: '';
               left:5px;
               top:50%;
               margin-top:-5px;
               
            }.on::after{
                background-color:#04AE70;
            }
        }
    }
    .groug-right-view{
        position: absolute;
        bottom:20px;
        right:80px;
        z-index:99; 
        border:1px solid #a9a8a8;
        background-color: #00000080;
        padding:12px 20px;
        font-size:15px;
        color: #fff;
        text-align: center;
        .choose-land{
            margin: 8px 0px;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
   .groug-view{
        position: absolute;
        bottom:10px;
        left:10px;
        z-index:99;
        .groug-list{
            background-color: #fff;
            display: flex;
            justify-content: flex-start;
            .item{
                height:36px;
                line-height:36px;
                padding:0 12px;
                font-size:14px;
                cursor: pointer;
            }.on{
                background-color: #04AE70;
                color:#fff;
            }
        }
   }
}
  </style>
  